#include "tcpclient.h"

TcpClient::TcpClient(std::string addr, int port) : addr_(addr), port_(port){
}

bool TcpClient::start(){
    /* 客户程序开始建立 sockfd描述符  */
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr,"Socket Error:%s\a\n",strerror(errno));
        return 1;
    }

    /* 客户程序填充服务端的资料       */
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;


    if(inet_aton(addr_.c_str(),&server_addr.sin_addr) == 0) //服务器的IP地址来自程序的参数
    {
        printf("Server IP Address Error!\n");
        exit(1);
    }

    server_addr.sin_port = htons(port_);
    socklen_t server_addr_length = sizeof(server_addr);
    /* 客户程序发起连接请求         */
    if(connect(sockfd, (struct sockaddr *)(&server_addr), server_addr_length) == -1) {
        fprintf(stderr,"Client Connect Error:%s\a\n",strerror(errno));
        return 1;
    }


    return 0;
}

void TcpClient::stop() {
    /* 结束通讯     */
    close(sockfd);
}

int TcpClient::ReadData(std::string &Data) {
    /* 开始读数据           */
    int nbytes;
    char buffer[BUF_SIZE];
    bzero(buffer, BUF_SIZE);
    nbytes = recv(sockfd,buffer,BUF_SIZE,0);      //= read(sockfd,buffer,BUF_SIZE)) == -1
    if (nbytes < 0) {
        fprintf(stderr,"Read Error:%s\n",strerror(errno));
        return -1;
    }

    if (nbytes == 0) {
        Data = "";
        return 0;
    }

    //buffer[nbytes]='\0';
    Data = buffer;
    //printf("I have sent:%s\n", buffer);
    //std::cout <<  Data ;
    return nbytes;
}

int TcpClient::WriteData(std::string Data) {
    /* 开始读数据           */
    int wbytes;
    if ((wbytes = write(sockfd,Data.c_str(),Data.size())) == -1) {
        fprintf(stderr,"write Error:%s\n",strerror(errno));
        return -1;
    }

    if (wbytes == 0) {
        return 0;
    }

    printf("I have sent:%s\n", Data.c_str());

    return wbytes;
}

TcpClient::~TcpClient() {
    //stop();
}

/*int main() {
    TcpClient t;
    t.Start();
    std::string d;
    t.WriteData(std::string("heart"));
    while (t.ReadData(d) > 0);
    return 0;
}*/
